//
//  LSZFavoritesListDetailsViewController.m
//  JKFuYinProject
//
//  Created by 九酷 on 2018/5/15.
//  Copyright © 2018年 LC. All rights reserved.
//

#import "LSZFavoritesListDetailsViewController.h"
#import "NetworkTool+LCAVPlay.h"

@interface LSZFavoritesListDetailsViewController ()
@property(nonatomic,assign) NSInteger cliclMoveWhereRow;
@end

@implementation LSZFavoritesListDetailsViewController
#pragma mark - 歌曲的详情   专辑的详情再跳到这个界面
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self InfoNotificationSongCollectionDeleted];
    [LCFloatingWindow sharedInstance].hidden = NO;
}
#pragma mark  - 得到数据
-(void)InfoNotificationSongCollectionDeleted
{
    [LSZRequestResolutionDic getsongList:self.id_id type:self.type page:@"1" fuid:self.fuid :^(BOOL isOk, NSString * string, LSZSongCollectionListManager * mg) {
        if (isOk == YES) {
            self.songCollectionListManager = mg;
            if(mg.arrayData.count == 0){
                LSZEmptyDataVC * emptyDataVC = [[LSZEmptyDataVC alloc]init];
                [emptyDataVC showWithView:self.tableViewFavoritesListDetails];
            }
            [self.tableViewFavoritesListDetails reloadData];
        }else{
            [self setStringWarning:string];
        }
    }];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [LCFloatingWindow sharedInstance].hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.stringTitle;

    [self.tableViewFavoritesListDetails registerClass:[LSZRandombroadcastHeaderCell class] forHeaderFooterViewReuseIdentifier:@"LSZRandombroadcastHeaderCell"];
    [self.tableViewFavoritesListDetails registerClass:[LSZNewWithPlusSignAudioTableViewCell class] forCellReuseIdentifier:@"LSZNewWithPlusSignAudioTableViewCell"];

    NSString * stringCollection = [NSString stringWithFormat:@"%@Collection",@"LSZFavoritesListDetailsViewController"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(LSZFavoritesListDetailsViewControllernSuccessfulCollection:) name:stringCollection object:nil];//收藏歌曲成功的通知

    NSString * stringNewSongList = [NSString stringWithFormat:@"%@newSongList",@"LSZFavoritesListDetailsViewController"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(FavoritesListDetails) name:stringNewSongList object:nil];//点击新创文件夹

    NSString * stringVC = @"LSZFavoritesListDetailsViewController";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InfoNotificationFavoritesListDetailsViewVC) name:stringVC object:nil];//收藏歌曲分享的通知
    NSString * strDownload = [NSString stringWithFormat:@"%@Download",@"LSZFavoritesListDetailsViewController"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InfoNotificationFavoritesListDetailsViewVCDownload) name:strDownload object:nil];//收藏歌曲成功的通知

    NSString * strDelete = [NSString stringWithFormat:@"%@DeleteLSZ",@"LSZFavoritesListDetailsViewController"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InfoNotificationFavoritesListDetailsVCDelete) name:strDelete object:nil];//点击删除的通知
    //安装播放歌曲发生变化的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(musicPlayerPlayingSongDidChangedNotification:) name:LCMusicPlayerPlayingSongDidChangedNotification object:_LCPlayer];
    @weakify(self)
    [LCFloatingWindow sharedInstance].didPushPlayPage = ^{
        @strongify(self)
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"LCPlayStoryboard" bundle:nil];
        UIViewController *controller = [sb instantiateInitialViewController];
        [self presentViewController:controller animated:YES completion:nil];
    };
}
- (void)musicPlayerPlayingSongDidChangedNotification:(NSNotification *)notification {
    [self.tableViewFavoritesListDetails reloadData];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (ScreenWidth == 320) {
        //5
        return 45;
    }else if(ScreenWidth == 375){
        // 6 7
        return 50;
    }
    else {
        //plus
        return 58;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (ScreenWidth == 320) {
        //5
        return 35;
    }else if(ScreenWidth == 375){
        // 6 7
        return 40;
    }
    else {
        //plus
        return 48;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.songCollectionListManager.arrayData.count;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UITableViewHeaderFooterView * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"foot"];
    if (!cell) {
        cell = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:@"foot"];
    }
    cell.backgroundView.backgroundColor = [UIColor clearColor];
    return cell;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    LSZRandombroadcastHeaderCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"LSZRandombroadcastHeaderCell"];
    [cell.imageViewPlay tapGesture:^(UIGestureRecognizer *ges) {
        [self clickPlay];
    }];
    [cell.label tapGesture:^(UIGestureRecognizer *ges) {
        [self clickPlay];
    }];
    [cell.butPaly addTarget:self action:@selector(clickPlay) forControlEvents:UIControlEventTouchUpInside];
    //当前播放列表clickNowPlayLists
//    cell.imageViewList.hidden = YES;

//    __weak typeof(self) weakSelf = self;
//    [cell.imageViewList tapGesture:^(UIGestureRecognizer *ges) {
//        [weakSelf clickList];
//    }];
//    cell.nowListsBlock = ^{
//        [weakSelf clickList];
//    };
//    [cell.butList addTarget:self action:@selector(clickList) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LSZNewWithPlusSignAudioTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZNewWithPlusSignAudioTableViewCell" forIndexPath:indexPath];
    if (indexPath.row >= self.songCollectionListManager.arrayData.count) {
        return cell;
    }
    cell.labelNumber.text = [NSString stringWithFormat:@"%ld",(long)indexPath.row+1];
    LSZSongCollectionListMg * mg = nil;
    mg = self.songCollectionListManager.arrayData[indexPath.row];

    cell.labelSong.text = [NSString stringWithFormat:@"%@",mg.title];
    cell.labelAlbums.text = [NSString stringWithFormat:@"%@",mg.album];
    //耳机
    [LSZSpecialPackaging adaptiveWidth:cell.labelAlbums str:cell.labelAlbums.text sizeMaxWidth:ScreenWidth sizeMaxHeight:cell.labelAlbums.frame.size.height];
    CGRect rect = cell.imageViewHeadset.frame;
    rect.origin.x = CGRectGetMaxX(cell.labelAlbums.frame)+10;
    cell.imageViewHeadset.frame = rect;
    //次数
    CGRect rectPlays = cell.labelPlaysNumber.frame;
    rectPlays.origin.x = CGRectGetMaxX(cell.imageViewHeadset.frame)+2;
    rectPlays.size.width = ScreenWidth-CGRectGetMaxX(cell.imageViewHeadset.frame)-10;
    cell.labelPlaysNumber.frame = rectPlays;
    cell.labelPlaysNumber.text = [NSString stringWithFormat:@"%@次",mg.click];

    cell.butAdd.tag = indexPath.row +1;
    [cell.butAdd addTarget:self action:@selector(clickAddDownload:) forControlEvents:UIControlEventTouchUpInside];

    if([(NullStringjudgment(NSStr(self.fuid))) isEqualToString:@""]){
        cell.butMove.hidden = NO;
    }else{
        cell.butMove.hidden = YES;
    }
    cell.butMove.tag = indexPath.row +1;
    [cell.butMove addTarget:self action:@selector(clickMoveDownload:) forControlEvents:UIControlEventTouchUpInside];
    ///判断是否是选中当前这首  ,  为主题颜色
    if (_LCPlayer.selectedIndex == indexPath.row && [cell.labelSong.text isEqualToString:_LCPlayer.playingSong.title] && [mg.album isEqualToString:_LCPlayer.playingSong.album]) {
        [cell didSelectRowCellWithIsSystemRed:YES];
    }else{
        [cell didSelectRowCellWithIsSystemRed:NO];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
#pragma mark  - 类别
-(void)clickMoveDownload:(UIButton *)but
{
    self.cliclMoveWhereRow = but.tag-1;
    LSZSongCollectionListMg * mg = nil;
    mg = self.songCollectionListManager.arrayData[self.cliclMoveWhereRow];
    LSZPopoverViewController * vc = [[LSZPopoverViewController alloc]init];
    [vc show];
    [vc selectIndexRowWith:1];//布局
    [vc getMusicId:mg.id_id];//这个id 删除的时候用的    不知分享和下载是不是这个
    [vc distinguishType:@"3"];
    [vc ChooseTableViewFrame:@"1"];//改变布局
    [vc fromWhichInterface:@"LSZFavoritesListDetailsViewController"];
}
#pragma mark - 新建文件夹
-(void)FavoritesListDetails
{
    //提示框添加文本输入框
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"创建新文件夹"
                                                                   message:@""
                                                            preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction* okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                     handler:^(UIAlertAction * action) {
                                                         for(UITextField *text in alert.textFields){
                                                             //响应事件//得到文本信息
                                                             NSLog(@"确定text = %@", text.text);
                                                             [self addNewFolder:text.text];
                                                         }
                                                     }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * action) {
                                                             //响应事件
                                                             NSLog(@"取消action = %@", alert.textFields);
                                                         }];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"输入新建文件夹名字";
    }];
    [alert addAction:okAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 添加新的文件夹名字
-(void)addNewFolder :(NSString *)string
{
    [LSZRequestData TheAdditionOfFavorites:@"3" name:string :^(BOOL isOK, NSString * string, NSDictionary * dic) {
        if (isOK == YES) {
            NSLog(@"%@",dic);
            NSString * cat =  NullStringjudgment(NSStr(dic[@"data"][@"cat"]));;
            LSZSongCollectionListMg * mg = nil;
            mg = self.songCollectionListManager.arrayData[self.cliclMoveWhereRow];
            [LSZRequestData getSongCollection:cat :mg.id_id :^(BOOL isOk, NSString * string, NSDictionary * dic) {
                [self setStringWarning:string];
            }];
        }else{
            [self setStringWarning:string];
        }
    }];
}
#pragma mark - 接受删除的通知
-(void)InfoNotificationFavoritesListDetailsVCDelete
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        LSZSongCollectionListMg * mg = nil;
        if (self.cliclMoveWhereRow < self.songCollectionListManager.arrayData.count) {
            mg = self.songCollectionListManager.arrayData[self.cliclMoveWhereRow];
        }else{
            [self setStringWarning:@"请重新选择删除的数据!"];
            return;
        }
        [LSZRequestData songCollectionDeleted:mg.id_big :^(BOOL isOK, NSString * str, NSDictionary * dic) {
            if (isOK == YES) {
                [self setStringWarning:@"歌曲删除成功!"];
                self.cliclMoveWhereRow = -1;
                [self InfoNotificationSongCollectionDeleted];
            }else{
                [self setStringWarning:str];
            }
        }];
    });


}
#pragma mark - 收藏成功提醒
-(void)LSZFavoritesListDetailsViewControllernSuccessfulCollection:(NSNotification *)notification
{
    NSLog(@"%@>>>>>",notification);
    NSDictionary * diction = notification.userInfo;
    if ([diction[@"ok"] isEqualToString:@"YES"]) {
        [self setStringWarning:@"收藏成功!"];
    }else{
        if([diction[@"str"] isEqualToString:@"取消成功"]){
            [self InfoNotificationSongCollectionDeleted];
        }
        [self setStringWarning:diction[@"str"]];
    }
}
#pragma mark - 下载
-(void)InfoNotificationFavoritesListDetailsViewVCDownload
{
    JKSongsMessStatus *songsMessStatus;
    LSZSongCollectionListMg * mg = nil;
    mg = self.songCollectionListManager.arrayData[self.cliclMoveWhereRow];
    NSDictionary *json = [mg yy_modelToJSONObject];
    songsMessStatus = [JKSongsMessStatus yy_modelWithJSON:json];
    [kNetworkTool downloadSongWithUrl:songsMessStatus];//下载歌曲文件
}
#pragma mark - 分享的按钮
-(void)InfoNotificationFavoritesListDetailsViewVC
{
    LSZSongCollectionListMg * mg = nil;
    mg = self.songCollectionListManager.arrayData[self.cliclMoveWhereRow];
//    [self shareMusicWithImageStr:@"我的_设置_关于" song:nil musicUrl:mg.fileUrl musicWebUrl:mg.shareUrl title:mg.title contentMessage:mg.singerName];
    [self shareAudioWithImageArray:@[mg.image] url:mg.fileUrl musicWebURL:mg.shareUrl title:mg.title contentMessage:mg.singerName type:(SSDKContentTypeAudio)];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self didSelectRowWithIndexPath:indexPath];
}
#pragma mark - 点击
- (void)clickPlay {
    NSLog(@"全部播放按钮");
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self didSelectRowWithIndexPath:indexPath];
}
#pragma mark - 点击播放一首
- (void)didSelectRowWithIndexPath:(NSIndexPath *)indexPath {
    LSZSongCollectionListMg * mg = nil;
    mg = self.songCollectionListManager.arrayData[indexPath.row];
    if (_LCPlayer.selectedIndex == indexPath.row && [_LCPlayer.playingSong.id isEqualToString:[NSString stringWithFormat:@"%@",mg.id_id]]) {
        return;
    }
    NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < self.songCollectionListManager.arrayData.count; i++) {
        NSDictionary *json = [self.songCollectionListManager.arrayData[i] yy_modelToJSONObject];
        [mutableArray addObject:json];
    }
    NSLog(@"mutableArray.copy = %@", mutableArray.copy);
    [LSZSpecialPackaging addPlaylistWithArrayData:mutableArray.copy];
    LCPlaylist *playlistTest = _PlaylistMgr.allPlaylists.firstObject;
    _LCPlayer.songs = playlistTest.allSongs;
    if (_LCPlayer.songs != nil) {
        [_LCPlayer playAtIndex:indexPath.row isSelectPlay:YES];
    }
    [LSZRequestData songClickOnTheDataUpdates:mg.id_id :^(BOOL isOk, NSString * str, NSDictionary * dic) {
        if (isOk == YES) {
            //点击数更新OK
            mg.originalClick = [NSString stringWithFormat:@"%d",[mg.originalClick intValue]+1];
            mg.click  = [LSZSpecialPackaging theNumberViewsForTheAlbumAhanges:mg.originalClick];
            [UIView performWithoutAnimation:^{
                [self.tableViewFavoritesListDetails  reloadData];
            }];
        }
    }];
}
#pragma mark - 当前列表的点击事件
//- (void)clickList {
//    NSLog(@"当前列表的点击事件");
////    [self example7];
//}
#pragma mark - 添加按钮的点击事件
- (void)clickAddDownload:(UIButton *)butAdd {
    if ([_LCPlayer.playingSong.singerName isEqualToString:@"圣经新约"] || [_LCPlayer.playingSong.singerName isEqualToString:@"圣经旧约"]) {
        return;//播放圣经  不能添加歌曲到当前列表
    }
    LCPlaylist *playlist = [LCPlaylist new];
    if (_LCPlayer.songs) {
        playlist.songs = _LCPlayer.songs.mutableCopy;
    }
    JKSongsMessStatus *songsMessStatus;
    NSDictionary *json = [self.songCollectionListManager.arrayData[(butAdd.tag - 1)] yy_modelToJSONObject];
    songsMessStatus = [JKSongsMessStatus yy_modelWithJSON:json];
    
    [self setStringWarning:[NSString stringWithFormat:@"添加歌曲    <<%@>>  成功",songsMessStatus.title]];
    [playlist addSongSelectedIndexLater:songsMessStatus];
    _LCPlayer.songs = playlist.allSongs;
    if (_LCPlayer.songs != nil) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"LCMusicPlayerAddSongNotification" object:self userInfo:nil];
    }
}

-(UITableView *)tableViewFavoritesListDetails
{
    if (_tableViewFavoritesListDetails == nil) {
        _tableViewFavoritesListDetails = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-60) style:UITableViewStyleGrouped];
        _tableViewFavoritesListDetails.delegate = self;
        _tableViewFavoritesListDetails.dataSource = self;
        _tableViewFavoritesListDetails.estimatedRowHeight =0;
        _tableViewFavoritesListDetails.estimatedSectionFooterHeight =0;
        _tableViewFavoritesListDetails.estimatedSectionHeaderHeight =0;
        _tableViewFavoritesListDetails.separatorInset = UIEdgeInsetsMake(0, 20, 0, 20);
        _tableViewFavoritesListDetails.separatorColor = divider;
        [self.view addSubview:_tableViewFavoritesListDetails];
    }
    return _tableViewFavoritesListDetails;
}
@end
